#! /bin/bash

_bash_lib_dir="${_bash_conf_dir}/lib"

color_red=""

_bash_precmd_x()
{
    # python virtual env
    local _v=${VIRTUAL_ENV##*/}
    if [ ${_v} ]; then
        _v="\[\033[0;38;5;245m\]:\[\033[00m\]\[\033[1;38;5;142m\]${_v:0:3}\[\033[00m\]"
    fi
    # git branch
    local _b=$(_gitbrc)
    if [ ${_b} ]; then
        _b="\[\033[0;38;5;245m\]:\[\033[00m\]\[\033[1;38;5;172m\]${_b:0:3}\[\033[00m\]"
    fi
    # shell ps1
    PS1="\[\e]0;\u@\h: \w\a\]\[\033[1;38;5;71m\]\u@\h\[\033[00m\]\[\033[0;38;5;245m\]:\[\033[00m\]\[\033[1;38;5;105m\]\w\[\033[00m\]${_v}${_b}\$ "
}

source "$_bash_lib_dir/git.bash"

function _bash_precmd() {
    local last_command_status=$?

    local bash_logo="->"

    # define color
    local color_none="\[\e[0m\]"
    local color_success="\[\e[1;32m\]"
    local color_error="\[\e[1;31m\]"
    local color_pwd="\[\e[1;34m\]"
    local color_venv="\[\e[33m\]"
    local color_repo="\[\e[33m\]"

    # define git repo
    local repo_dirty="*"
    local repo_ahead="↑"
    local repo_behind="↓"
    local repo_diverged="!"

    local ps_title=""
    local ps_logo=""
    local ps_repo=""
    local ps_venv=""

    # title
    ps_title="\[\e]0;\u@\h: \w\a\]"

    # cmd status
    if [[ -n $BASH_LOGO ]]; then
        bash_logo=$BASH_LOGO
    fi

    if [[ $last_command_status == 0 ]]; then
        ps_logo="${color_success}${bash_logo}${color_none}"
    else
        ps_logo="${color_error}${bash_logo}${color_none}"
    fi

    # python virtualenv
    if [[ -n $VIRTUAL_ENV ]]; then
        ps_venv=" ${color_venv}(${VIRTUAL_ENV##*/})${color_none}"
    fi

    # pwd
    ps_pwd=" ${color_pwd}\W${color_none}"

    # git repo
    if git_is_repo; then
        # repo branch
        ps_repo=" ${color_repo}$(git_branch_name)${color_none}"

        # repo branch status
        local bs=""

        if git_is_touched; then
            bs=$repo_dirty
        fi

        if [[ -z $bs ]]; then
            bs="$(git_ahead $repo_ahead $repo_behind $repo_diverged)"
        fi

        ps_repo+=$bs
    fi

    PS1="${ps_title}${ps_logo}${ps_venv}${ps_pwd}${ps_repo} "
}

PROMPT_COMMAND=_bash_precmd
